package org.grow.present.dto;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author: xwg
 * @CreateDate: 2025/9/19
 */

@Data
public class ChatMessage {
    private String type; // "JOIN", "CHAT", "LEAVE"
    private String content;
    private String sender;
    private String timestamp;

    // 构造函数
    public ChatMessage() {}

    public ChatMessage(String type, String content, String sender) {
        this.type = type;
        this.content = content;
        this.sender = sender;
        this.timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
    }


    // 转换为JSON
    public String toJson() {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            return "{\"error\": \"JSON conversion error\"}";
        }
    }

    // 从JSON解析
    public static ChatMessage fromJson(String json) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(json, ChatMessage.class);
        } catch (IOException e) {
            return new ChatMessage("ERROR", "Invalid message format", "System");
        }
    }
}
